﻿using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Syspetro.Deploy.Jwt
{
    public class TokenMemoryCache : ITokenCache
    {
        private readonly IMemoryCache Cache;
        public TokenMemoryCache(IMemoryCache memoryCache)
        {
            Cache = memoryCache;
        }
        public TimeSpan ExpireTimeSpan { get; set; }
        public void Add(Guid userid, Guid id, string token)
        {
            if (Cache.TryGetValue(userid, out Guid tokenid))
            {
                Cache.Remove(tokenid);
                Cache.Set(id, token, ExpireTimeSpan);
                Cache.Set(userid, id);
            }
            else
            {
                Cache.Set(id, token, ExpireTimeSpan);
                Cache.Set(userid, id);
            }
        }
        public bool Refresh(Guid id, string token)
        {
            if (Cache.TryGetValue(id, out string tokened))
            {
                Cache.Set(id, tokened, ExpireTimeSpan);
                return true;
            }
            else
            {
                return false;
            }
        }
        public string GetByToken(Guid id)
        {
            return Cache.Get<string>(id);
        }
        public void RemoveByUser(Guid userid, Guid tokenid)
        {
            if (Cache.TryGetValue(userid, out string _token))
            {
                if (_token == tokenid.ToString())
                {
                    Cache.Remove(_token);
                    Cache.Remove(userid);
                }
            }
        }
    }
}
